import axios from 'axios'
import { getToken } from '@/utils/auth'
import { Toast, TOAST_TYPE } from '@/TUIKit/components/common/Toast/index';

// 是否显示重新登录
export let isRelogin = { show: false };

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: process.env.VUE_APP_BASE_API,
  // 超时
  timeout: 10000
})

// request拦截器
service.interceptors.request.use(config => {
  if (getToken()) {
    // config.headers['token'] = '986924c6e53244448b0a9f55cfcb89aa'
    // 让每个请求携带自定义token 请根据实际情况自行修改
    config.headers['token'] = getToken() 
  }
  
  return config
}, error => {
    console.log(error)
    Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use(res => {
    // 未设置状态码则默认成功状态
    const code = res.data.code || 200;
    
    if (code === 200) {
      return res.data.result
    } else if (code === 999) {
      Toast({
        message: res.data.message,
        type: TOAST_TYPE.ERROR,
      });
    } else {
      // ElMessage({ message: res.data.message, type: 'error', duration: 5 * 1000 })
      return Promise.reject(new Error(res.data.message))
    }
  },
  error => {
    console.log('err' + error)
    // ElMessage({ message: res.data.message, type: 'error', duration: 5 * 1000 })
    return Promise.reject(error)
  }
)


export default service
